import 'package:dio/dio.dart';
import 'package:enjoy_life/utils/EventsBus.dart';
import 'package:enjoy_life/utils/NetworkService.dart';
import 'package:enjoy_life/utils/Toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {
    'id': "1",
    'avatar': '',
    'nickName': "用户名",
  };

  final TextEditingController _nickNameController = TextEditingController();

  @override
  void initState() {
    super.initState();

    setState(() {
      userInfo = widget.userInfo;
      _nickNameController.text = userInfo['nickName'] ?? '默认用户';
    });
  }

  // 修改用户昵称
  Future<void> editNickname() async {
    String nickName = _nickNameController.text;
    if (nickName.isEmpty) {
      return CustomToast.error('昵称不能为空');
    }

    if (nickName.length > 10) {
      return CustomToast.error('昵称不能超过10个字符');
    }

    try {
      await http.put('/userInfo', data: {'nickName': nickName});
      eventBus.fire(LoginEvent());
      CustomToast.success('修改成功');
    } catch (e) {
      CustomToast.success('网络出现错误');
    }
  }

  // 上传图片
  void selectAvatar() async {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 200,
              width: MediaQuery.of(context).size.width,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ListTile(
                      leading: const Icon(Icons.camera_alt),
                      title: const Text('拍照'),
                      trailing: const Icon(Icons.arrow_forward_ios_sharp),
                      onTap: () async {
                        final ImagePicker picker = ImagePicker();
                        final XFile? photo =
                            await picker.pickImage(source: ImageSource.camera);
                        if (photo != null) {
                          updateAvatar(photo.path);
                        }
                      },
                    ),
                    ListTile(
                      leading: const Icon(Icons.photo),
                      title: const Text('相册'),
                      trailing: const Icon(Icons.arrow_forward_ios_sharp),
                      onTap: () async {
                        final ImagePicker picker = ImagePicker();
                        final XFile? image =
                            await picker.pickImage(source: ImageSource.gallery);
                        if (image != null) {
                          updateAvatar(image.path);
                        }
                      },
                    )
                  ]));
        });
  }

  // 上传图片
  Future<void> updateAvatar(String imagePath) async {
    try {
      // 1.包装数据
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(imagePath),
        "type": "avatar",
      });
      var res = await http.post('/upload', data: formData);
      if (res['code'] != 10000) return CustomToast.error('上传图片失败');
      setState(() {
        userInfo['avatar'] = res['data']['url'];
        CustomToast.success('上传图片成功');
      });
    } catch (e) {
      CustomToast.error('上传图片失败');
    } finally {
      // 关闭弹层
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: GestureDetector(
                          onTap: () {
                            selectAvatar();
                          },
                          child: userInfo['avatar'] != null
                              ? Image.network(userInfo['avatar'],
                                  width: 30, height: 30)
                              : Image.asset('assets/images/avatar_1.jpg',
                                  width: 30, height: 30),
                        )),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  onEditingComplete: () {
                    // 回车修改昵称
                    editNickname();
                  },
                  decoration: InputDecoration(
                      hintText: '请输入昵称', border: InputBorder.none),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
